package com.wt.test.sre.provider.service;

import com.wt.test.sre.common.component.BaseServiceImpl;
import com.wt.test.sre.common.util.RedisUtil;
import com.wt.test.sre.provider.entity.BookDO;
import com.wt.test.sre.provider.mapper.BookMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author qiyu
 * @since 2025/9/18
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BookService extends BaseServiceImpl<BookMapper, BookDO> {
    
    private static final String CACHE_KEY_PREFIX = "book:";
    
    private final RedisUtil redisUtil;
    
    /**
     * 创建书籍
     *
     * @param name 书籍名称
     * @return 书籍ID
     */
    @Transactional(rollbackFor = Exception.class)
    public Long createBook(String name) {
        log.info("create book, name: {}", name);
        BookDO book = (BookDO) redisUtil.get(CACHE_KEY_PREFIX + name);
        if (Objects.nonNull(book)) {
            log.info("create book failed, book already exists, name:{}", name);
            throw new RuntimeException("create book failed, book already exists, name:" + name);
        }
        book = BookDO.builder()
                .name(name)
                .build();
        save(book);
        redisUtil.set(CACHE_KEY_PREFIX + name, book);
        return book.getId();
    }
}
